#include "util.hpp"

#include <cstdio>
#include <vector>
#include <functional>

using func_t = std::function<void()>;

#define INIT(v)                \
    do                         \
    {                          \
        v.push_back(printLog); \
        v.push_back(downLoad); \
        v.push_back(execSql);  \
    } while (0)

#define EXEC_OTHER(cbs)            \
    do                             \
    {                              \
        for (const auto &cb : cbs) \
            cb();                  \
    } while (0)

int main()
{
    setNonBlock(0); // 设置0号文件描述符(键盘)为非阻塞状态

    std::vector<func_t> v;
    INIT(v);

    char buffer[1024];
    while (true)
    {
        printf(">>> ");
        fflush(stdout);
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s - 1] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }
        else if (s == 0)
        {
            std::cout << "read end!" << std::endl;
            break;
        }
        else
        {
            // 1.当我不输入时，底层没有数据，算错误吗？不算，只不过以错误的形式返回了
            // 2. 那怎么区分是真正的错误还是底层没有数据呢？单纯返回值无法区分，所以要用到错误码
            // EAGAIN or EWOULDBLOCK
            // std::cout << "result: " << s << std::endl;
            // std::cout << "errno: " << errno << std::endl;
            // std::cout << "err_msg: " << strerror(errno) << std::endl;
            // std::cout << "EAGAIN: " << EAGAIN << std::endl;
            // std::cout << "EWOULDBLOCK: " << EWOULDBLOCK << std::endl;

            if (errno == EAGAIN /*|| errno == EWOULDBLOCK*/)
            {
                // 只是暂时无数据，先执行别的任务，等一下再去调用read
                std::cout << "我没错，我只是暂时没有数据" << std::endl;
                EXEC_OTHER(v);
            }
            else if (errno == EINTR)
            {
                // 被系统调用中断，没事，继续读
                continue;
            }
            else
            {
                // 这里才是真正的错误
                std::cout << "err_msg: " << strerror(errno) << std::endl;
                break;
            }
        }
        sleep(1);
    }
    return 0;
}